package engine.newUi
{
	import com.greensock.TweenLite;
	
	import engine.GameData;
	import engine.control.loading.MultLoader;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ResPath;
	import engine.data.RoleVo;
	import engine.data.Scene;
	import engine.event.SceneEvent;
	import engine.flag.PlayerActionFlag;
	import engine.flag.ResourcesPath;
	import engine.logic.MenuListManager;
	import engine.logic.SceneTransfer;
	import engine.scene.SceneChangeManager;
	import engine.tip.TipsMainLogic;
	import engine.ui.AlertUI;
	import engine.ui.UIManage;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.setTimeout;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	
	/**
	 *世界地图 
	 * @author yanghr
	 * 
	 */
	public class WorldMapLogic
	{
		private static var _self:WorldMapLogic;
		
		private const SCALE:Number=0.5;
		private const SPEED:Number=100;
		
		private var MAX_SEE_WIDTH:Number=1280;
		private var MAX_SEE_HEIGHT:Number=768;
		
		private const LEVEL:String	=	"levelNeed";
		private var _ui:WorldMapUI;
		private var _model:ModelLocator;
		private var _scene:Scene;
		private var _role:RoleVo;
		private var _bind:BindManage;
		private var _tips:TipsMainLogic;
		
		private var _bindLevelFlag:int	=	-1;
		private var _bindModelFlag:int	=	-1;
		private var _maxWidth:int 
		private var _maxHeight:int
		/**
		 *人物模型 
		 */		
		private var _roleModel:MovieClip;
		private var _isLoading:Boolean;
		private var _isLoaded:Boolean=false;
		private var _isLaodedMap:Boolean=false;
		private var _targetMc:MovieClip;
		private var _tempPoint:Point=new Point;
		private var _configMap:Object=new Object;
		private var _rec:Rectangle=new Rectangle;
		
		private var _callBackArr:Array=[];
		public static function getInstance():WorldMapLogic
		{
			if(_self==null)
			{
				_self=new WorldMapLogic();
			}
			return _self;
		}
		public function get ui():WorldMapUI
		{
			return _ui
		}
		public function WorldMapLogic()
		{
			_ui	=	new WorldMapUI();
		}
		 public function  Init():void
		{
			 _model=ModelLocator.getInstance();
			 _scene	=	_model.scene;
			 _role	=	_scene.Role;
			 _bind	=	BindManage.getInstance();
			 _tips	=	TipsMainLogic.instance;
			 _ui.mapMC.mouseEnabled=false
			 _maxWidth= int(
				 ModelLocator.getInstance().mainIni.getContent("stageConfig","width")
			 );
			 _maxHeight = int(
				 ModelLocator.getInstance().mainIni.getContent("stageConfig","height") 
			 );
			 
			 _ui.addChild(_gr)
			 //拖拽
			 stage.addEventListener(Event.RESIZE,function(e:Event):void{
//			 	WorldMapLogic.getInstance().dragAble;
				 if(_isLoaded&&_ui.parent)
					 _ui.modifyPostion();
//				 trace("WorldMapLogic.enclosing_method(e)",_ui.x,_ui.y);
//				 _gr.graphics.clear();
//				 _gr.graphics.beginFill(0xffffff*Math.random());
//				 _gr.graphics.drawRect(0,0,ui.width,ui.height);
//				 _gr.graphics.endFill()
				 
			 })
//			_ui.windowBG.visible=false;
		 }
		 private var  _gr:Sprite=new Sprite
		 private function loadAll():void
		 {
			 MultLoader.getInstance().load([ResPath.SWF+"WorldMap.swf",ResourcesPath.getRoleModel(_role)],true,loadComplete,null);
			 _isLoading=true
		 }
		 private function loadComplete():void
		 {
			 _ui.mapMC.source=MultLoader.getInstance().getSourceByUrl(ResPath.SWF+"WorldMap.swf");
			 onLoadImg( _ui.mapMC.content as DisplayObjectContainer);
			 _isLoaded=true;
			 _isLoading=false;
			 loadOver(MultLoader.getInstance().getSourceByUrl(ResourcesPath.getRoleModel(_role))as MovieClip,null);
			 BeforeShow();
			 callBack();
		 }
		 private var _rollOverMc:MovieClip;
		 public function set rollOverMc(value:MovieClip):void
		 {
			 if(_rollOverMc)
			 {
				 _rollOverMc.gotoAndStop(1)
			 }
			 _rollOverMc	=	value;
			 if(_rollOverMc)
			 {
				 _rollOverMc.gotoAndStop(2);
			 }
		 }
		 private function onLoadImg(val:DisplayObjectContainer):void
		 {
//			 MAX_SEE_HEIGHT=val.height;
//			 MAX_SEE_WIDTH=val.width;
			 var $this:Object=this;
			 _isLaodedMap=true;
			 val.mouseChildren=val.mouseEnabled=true;
			 for (var i:int = 0; i < val.numChildren; i++) 
			 {
				 var mc:MovieClip=val.getChildAt(i) as MovieClip;
				 if(mc)
				 {
					 var obj:Object=StaticIni.getIniObj("SceneMovePoint"+mc.name);
					 mc.gotoAndStop(1);
					 mc.addEventListener(MouseEvent.ROLL_OVER,function(e:Event):void{
						 $this.rollOverMc=e.currentTarget as MovieClip
					 })
					 if(obj)
					 {
						 _configMap[mc.name]=obj;
					 }
					 else
					 {
//						 trace("Error~WorldMapLogic.onLoadImg(val)",mc.name);
						 
					 }
				 }
			 }
			 if(_ui.windowBG)
			 {
				 _ui.windowBG.width	=	val.width;
				 _ui.windowBG.height	=	val.height;
			 }
			 _model.addEventListener(SceneEvent.SceneLoaded,function (e:Event):void{
				 var id:int= GameData.SceneConfig
				 var mc:MovieClip=_ui.mapMC.content["_"+id] as MovieClip;
			 });
		 }
		 private function callBack():void
		 {
			 for (var j:int = 0; j < _callBackArr.length; j++) 
			 {
				 var func:Function=_callBackArr[j];
				 var plist:*=_plistArr[j];
				 if(plist is Array)
					 func.apply(this,plist);
				 else 
					 func.apply(this,[plist])
			 }
			 _callBackArr=[];
			 _plistArr=[];
		 }
	
		private var currModel:int=0;
		private function loadOver(mc:MovieClip,pl:Array):void
		{
			if(mc)
			{
				_isLoaded=true
				if(_roleModel&&_roleModel.stage)
				{
					_roleModel.parent.removeChild(_roleModel);
				}
				currModel = _role.ModelId;
				if(mc.numChildren == 1 && mc.totalFrames == 1 )
				{
					mc = mc.getChildAt( 0 ) as MovieClip;
				}else
				{
					mc = ResManager.copy( mc ) as  MovieClip;
				}
				mc.scaleX	=	mc.scaleY	=	SCALE;
				_roleModel	=	mc;
				_roleModel.gotoAndPlay(PlayerActionFlag.NormalWait);
//				changeModelPoint()
				_isLoading=false;
				modelStop();
				reSetPos();
			}
			else
			{
//				trace("Error~WorldMapLogic.loadOver(mc, pl)没人物模型");
				_roleModel			=	ResManager.newResClass("custSkin_86") as MovieClip;
			}
			if(_roleModel.stage==null)
				_ui.addChild(_roleModel);
//			if(_isLaodedMap)
//			{
//				callBack();
//			}
		}
		/**
		 * 取在进入帮派场景前的场景
		 * 或者自己所在的真场景 
		 * @return 
		 * 
		 */		
		private function get currentMapID():int
		{
			return int(_role.GetPropertiesEx("BeforeGuildScene"))	|| GameData.SceneConfig;
		}
		private function reSetPos():void
		{
			var id:int=currentMapID;
			var mc:MovieClip=_ui.mapMC.content["_"+id] as MovieClip;
			if(mc)
			{
				_tempPoint.x=mc.x+mc.width/2;
				_tempPoint.y=mc.y+mc.height/2;
				changeModelPoint(_ui.globalToLocal(_ui.mapMC.content.localToGlobal(_tempPoint)));
			}
			else
			{
//				trace("Error~WorldMapLogic.reSetPos(mc, pl)没有这个id对应的城市？？？",id);
				
			}
		}
		private var _isRunning:Boolean=false;
		private function runToPoint(point:Point):void
		{
			_isRunning=true;
			modelRun();
			changeDirection(point.x-_roleModel.x>0)
			TweenLite.to(_roleModel,getDistance()/SPEED,{x:point.x,y:point.y,onComplete:endRun});
			function getDistance():Number
			{
				var p:Point=new Point(_roleModel.x,_roleModel.y);
				return Point.distance(p,point);
			}
		}
		private function changeDirection(isright:Boolean):void
		{
			_roleModel.scaleX=SCALE*(isright?1:-1)
		}
		private function endRun():void
		{
			modelStop();
			_isRunning=false;
			if(_targetMc&&_targetMc.name!="_"+GameData.SceneConfig)//currentMapID
			{
				setTimeout(transfer,500)
			}
			else if(_targetMc.name=="_"+currentMapID)
			{
				close(null);
			}
		}
		private function transfer():void
		{
			var obj:Object=_configMap[_targetMc.name]//_targetMc.name.substr(3);
			var id:String=obj["HrefEvent"]
			SceneTransfer.getInstance().tranferTo(id);
//			close(null)
		}
		private function changeModelPoint(point:Point):void
		{
			if(!_roleModel)return;
			_roleModel.x	=	point.x;
			_roleModel.y	=	point.y;
		}
		private function modelStop():void
		{
			if(!_roleModel)return;
			_roleModel.gotoAndPlay(PlayerActionFlag.NormalWait);
		}
		private function modelRun():void
		{
			if(!_roleModel)return;
			_roleModel.gotoAndPlay(PlayerActionFlag.Run);
		}
		 public function	BeforeShow():void
		{
			 UIManage.getInstance().hideOpenedUI();
			 if(!_isLoading&&!_isLoaded)
			 {
				 
				 loadAll();
				 return ;
			 }
			 else if(_isLoading)
			 {
//				 trace("WorldMapLogic.BeforeShow()xxx");
				return ;				 
			 }
			 else 
			 {
				 reSetPos();
			 }
			 addAllEventListener();
			 StageInfo.stage.dispatchEvent(new Event(Event.RESIZE))
		}
		public function get stage():Stage
		{
			return StageInfo.stage;
		}
		private var _starPoint:Point;
		 /**
		  *检测拖拽条件 
		  * @return 
		  * 
		  */		 
		 public function get dragAble():Boolean
		 {
			 if(_starPoint==null)
				 _starPoint=_ui.mapMC.parent.localToGlobal(new Point(_ui.mapMC.x,_ui.mapMC.y));
			 if(stage.stageWidth<MAX_SEE_WIDTH	||	stage.stageHeight<MAX_SEE_HEIGHT)
			 {
				 _ui.addEventListener(MouseEvent.MOUSE_DOWN,startDrag);
				 _ui.addEventListener(MouseEvent.MOUSE_UP,endDrag);
				 return true;
			 }
			 endDrag(null);
			 _ui.removeEventListener(MouseEvent.MOUSE_DOWN,startDrag);
			 _ui.removeEventListener(MouseEvent.MOUSE_UP,endDrag);
			 return false;
		 }
		 public function get dragRec():Rectangle
		 {
			 _rec.x=-_starPoint.x
			 _rec.y=-_starPoint.y
			 _rec.width=MAX_SEE_WIDTH-SceneChangeManager.getGameWidth()+_starPoint.x;
			 _rec.height=MAX_SEE_HEIGHT-SceneChangeManager.getGameHeight()+_starPoint.y;//stage.stageHeight;
//			 _ui.mapMC.content["graphics"].lineStyle(1,0xff00ff);
//			 _ui.mapMC.content["graphics"].drawRect(_rec.x,_rec.y,_rec.width,_rec.height);
			 return _rec
		 }
		 public function	AfterHide():void
		{
			removeAllEventListener()
		}
		 private function startDrag(e:Event):void
		 {
			 if(_ui.mapMC.content["closemap"]==e.target as DisplayObject)
			 {
				 return ;
			 }
			 _ui/*.mapMC*/.startDrag(false,dragRec);
		 }
		 private function endDrag(e:Event):void
		 {
			_ui/*.mapMC*/.stopDrag(); 
		 }
		 public function addAllEventListener():void
		 {
			 _ui.addEventListener(MouseEvent.CLICK,runClickHandle);
//			 dragAble
			 _ui.mapMC.content["closemap"].addEventListener(MouseEvent.CLICK,close);
			 if(_bindLevelFlag==-1)
			 {
				 _bindLevelFlag=_bind.BindProp(_role,ActorPropertyUI.LEVEL,this,"level")
			 }
//			 if(_bindModelFlag==-1)
//			 {
//				 _bindModelFlag=_bind.BindProp(_role,ActorPropertyUI.MODEL,this,"model")
//			 }
		 }
//		 public function set model(value:int):void
//		 {
//			 if(value == currModel)
//			 {
//				 return;
//			 }
//			 MultLoader.getInstance().load([ResourcesPath.getRoleModel(_role)],false,loadComplete1,null);
//		 }
//		 private function loadComplete1():void
//		 {
//			 loadOver(MultLoader.getInstance().getSourceByUrl(ResourcesPath.getRoleModel(_role))as MovieClip,null);
//		 }
		 public function set level(value:int):void
		 {
			 for  (var i:String in _configMap) 
			 {
				 _ui.mapMC.content[i].visible	=	value>=int(_configMap[i]["NeedLevel"]);
//				 _ui.mapMC.content[i].visible	=	true;//value>=int(_configMap[i]["NeedLevel"]);
				 _ui.mapMC.content[i][LEVEL]=int(_configMap[i]["NeedLevel"]);
				 
				 //把4个层叠的地图场景的低等级MC影藏掉
				 if(_role.getPlayerLevel()>=121)_ui.mapMC.content["_11030100"].visible = false;
				 if(_role.getPlayerLevel()>=126)_ui.mapMC.content["_11090100"].visible = false;
				 if(_role.getPlayerLevel()>=131)_ui.mapMC.content["_11020100"].visible = false;
				 if(_role.getPlayerLevel()>=141)_ui.mapMC.content["_11070100"].visible = false;
			 }
		 }
		 private function close(e:Event):void
		 {
			 if(!_isRunning)
			 	_ui.hide();
		 }
		 private function runClickHandle(e:MouseEvent):void
		 {
			 if(_roleModel)
			 {
				var mc:MovieClip=e.target as MovieClip
				 if(mc	&&	mc.hasOwnProperty(LEVEL))
				 {
					 if(mc[LEVEL]<=_role.getPlayerLevel())
					 {
						 if(mc.name == "_11140100")
							 MenuListManager.clickWorldMapScene(["_11140100","_11030100"]);
						 else if
							 (mc.name == "_11150100")MenuListManager.clickWorldMapScene(["_11150100","_11090100"]);
						 else if
							 (mc.name == "_11160100")MenuListManager.clickWorldMapScene(["_11160100","_11020100"]);
						 else if
							 (mc.name == "_11180100")MenuListManager.clickWorldMapScene(["_11180100","_11070100"]);
						 else
						 {
							 startMove(mc);
						 }
					 }
					 else
					 {
						 AlertUI.showAlert(StaticIni.getSwfLangStr("BuZhenStr_17"),StaticIni.getSwfLangStrVar("UIString_1000070",[mc[LEVEL],StaticIni.getSwfLangStr(mc.name.substr(1))]))
					 }
				 }
				 else
				 {
//					 trace("WorldMapLogic.runClickHandle(e)= = ");
					 
				 }
			 }
//				 runToPoint(e.localX,e.localY)
		 }
		 
		 
		 public function startMove(sceneMc:MovieClip):void
		 {
			 _targetMc		=	sceneMc;
			 var p:Point=new Point(_targetMc.x+_targetMc.width/2,_targetMc.y+_targetMc.height/2)
			 runToPoint(_ui.globalToLocal(_ui.mapMC.content.localToGlobal(p))); 
		 }
		 
		 public function getSceneMc(sceneMcName : String):MovieClip
		 {
			 return _ui.mapMC.content[sceneMcName];
		 }
		 
		 public function removeAllEventListener():void
		 {
			 _ui.removeEventListener(MouseEvent.CLICK,runClickHandle);
			 _ui.mapMC.content["closemap"].addEventListener(MouseEvent.CLICK,close);
			 _ui.removeEventListener(MouseEvent.MOUSE_DOWN,startDrag);
			 _ui.removeEventListener(MouseEvent.MOUSE_UP,endDrag);
			 if(_bindLevelFlag!=-1)
			 {
				 _bindLevelFlag=_bind.UnbindProp(_role,ActorPropertyUI.LEVEL,_bindLevelFlag);
			 }
			 if(_bindModelFlag!=-1)
			 {
				 _bindModelFlag=_bind.UnbindProp(_role,ActorPropertyUI.MODEL,_bindModelFlag);
			 }
		 }
		 private var _plistArr:Array=[];
		 /**
		  *自动寻路到sceneConfig 
		  * @param sceneConfig
		  * 
		  */		 
		 public function autoMove( sceneConfig : String ):void
		 {
			if( !_ui.created )
			{
				_ui.show();
			}
			if(_isLaodedMap)
			{
				realAutoMove(sceneConfig);
			}
			else
			{
				_plistArr.push(sceneConfig);
				_callBackArr.push(realAutoMove);
			}
			
		 }
		 private function realAutoMove( sceneConfig : String ):void
		 {
			 //寻找地图上的场景资源
			 var mapParent : MovieClip = _ui.mapMC.getChildAt( 0 ) as MovieClip;
			 //需要传送的场景，在地图上的图标
			 var mapMC	: MovieClip = mapParent[ "_" + sceneConfig ];
			 //移动
			 mapMC.dispatchEvent( new MouseEvent( MouseEvent.CLICK ) );
		 }
	}
}